<?php

namespace addons\csmwj\library\xapp\csmwj\utils;

use think\Config;
use app\common\library\Sms;
use addons\csmwj\library\xcore\xcore\utils\XcDaoUtils;
use addons\csmwj\library\xcore\xcore\utils\XcConfigUtils;
use addons\csmwj\library\xcore\xcore\utils\XcResponseUtils;

/**
 config.php
    [
        'name' => 'XpMessageNotifyUtils.emailtpl',
        'title' => '邮件模板',
        'type' => 'array',
        'content' => [],
        'value' => [
            '异地登录提醒' => '系统检测到您最近一次登录是异地登录。登录时间为：${time}，登录位置是：${city}。',
            '注册审核通过' => '恭喜您，您的帐号已经审核通过。',
            '注册审核退回' => '您的注册申请被退回，请关注。退回原因：${desc}',
            '修改手机号码验证码' => '您的验证码是:${code}',
            '通过手机注册验证码' => '您的验证码是:${code}',
            '通过手机找回密码验证码' => '您的验证码是:${code}',
            '通过手机登录验证码' => '您的验证码是:${code}',
        ],
        'rule' => '',
        'msg' => '',
        'tip' => '',
        'ok' => '',
        'extend' => '',
    ],
    [
        'name' => 'XpMessageNotifyUtils.mobiletpl',
        'title' => '短信模板',
        'type' => 'array',
        'content' => [],
        'value' => [
            '异地登录提醒' => 'SMS_123456789',
            '注册审核通过' => 'SMS_123456789',
            '注册审核退回' => 'SMS_123456789',
            '修改手机号码验证码' => 'SMS_123456789',
            '通过手机注册验证码' => 'SMS_123456789',
            '通过手机找回密码验证码' => 'SMS_123456789',
            '通过手机登录验证码' => 'SMS_123456789',
        ],
        'rule' => '',
        'msg' => '',
        'tip' => '',
        'ok' => '',
        'extend' => '',
    ],
 
 */
class XpMessageNotifyUtils
{
    /**
     * Copy from Sms#send
     */
    public static function sendccodesms($mobile, $code = null, $event = 'default')
    {
        $code = is_null($code) ? mt_rand(1000, 9999) : $code;
        $time = time();
        $ip = request()->ip();
        $sms = \app\common\model\Sms::create([
            'event' => $event,
            'mobile' => $mobile,
            'code' => $code,
            'ip' => $ip,
            'createtime' => $time
        ]);

        $ret = static::sendsms($mobile, $event, [
            'code' => $code
        ]);

        if (! $ret) {
            $sms->delete();
            return false;
        }
        return true;
    }

    /**
     * 发送短信
     */
    public static function sendsms($mobile, $tplname, $data)
    {
        $errmsg = "请到插件管理中配置：" . XcConfigUtils::xpconfig('addons_name') . " - 短信模板({$tplname})";
        $csmtpl = XcConfigUtils::config("XpMessageNotifyUtils.mobiletpl");
        if (! array_key_exists($tplname, $csmtpl)) {
            XcResponseUtils::error($tplname . "模板不存在，" . $errmsg);
        }
        $data = count($data) == 0 ? [
            'dual' => 'x'
        ] : $data;

        $ret = Sms::notice($mobile, $data, $csmtpl[$tplname]);

        if ($ret === false) {
            XcResponseUtils::error('发送失败，' . $errmsg);
        }
        return true;
    }

    /**
     * 发送邮件
     */
    public static function sendemail($email, $title, $tplname, $data)
    {
        // 如果邮箱格式不对,则不发送邮件
        if (strpos($email, '@') === false) {
            return;
        }

        $errmsg = "请到插件管理中配置：" . XcConfigUtils::xpconfig('addons_name') . " - 邮件模板({$tplname}):";

        $csmtpl = XcConfigUtils::config("XpMessageNotifyUtils.emailtpl");
        if (! array_key_exists($tplname, $csmtpl)) {
            XcResponseUtils::error($tplname . "模板不存在，" . $errmsg);
        }
        foreach ($data as $k => $v) {
            $$k = $v;
        }
        $contentdata = static::_evalstring($csmtpl[$tplname], $data);
        if ($email != null && $email != '') {
            $site = Config::get("site");
            $obj = \app\common\library\Email::instance();
            $ret = $obj->to($email)
                ->subject("[" . $site['name'] . "]" . $title)
                ->message($contentdata)
                ->send();
            if ($ret === false) {
                XcResponseUtils::error('发送失败，' . $errmsg);
            }
        }
    }

    private static function _evalstring($template, $data)
    {
        foreach ($data as $k => $v) {
            $$k = $v;
        }
        return eval('return "' . $template . '";');
    }


    /**
     * 给管理员帐号发送消息(目前支持邮箱和手机,未来可以扩展支持钉钉)
     */
    public static function notify($adminId, $tplname, $title, $data)
    {
        // 发送email
        $row = XcDaoUtils::getRowById(new \app\admin\model\Admin(),$adminId);
        if (! $row) {
            return;
        }
        $email = $row->email;
        if($email!=null && $email!=''){
            static::sendemail($email, $title, $tplname, $data);
        }
        

        // 发送短信
        if($row!=null && $row->mobile!=null && $row->mobile!=''){
            $mobile = $row->mobile;
            static::sendsms($mobile, $tplname, $data);
        }

        return true;
    }


    // public static function sendSMSAddonsMessage($mobile, $templateid, $data = [])
    // {
    //     $config = get_addon_config("qcloudsms");
    //     $sender = new SmsSingleSender($config['appid'], $config['appkey']);
    //     $result = $sender->sendWithParam("86", $mobile, $templateid, $data, $config['sign'], "", "");
    //     trace("sendMessage {$mobile} {$templateid}:".json_encode($data));
    //     return $result;
    // }

}
